package com.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.app.common.Result;
import com.app.mapper.IntegralRecordMapper;
import com.app.mapper.UserMapper;
import com.app.mapper.VoucherRecordMapper;
import com.app.model.AdminUserModel;
import com.app.model.IntegralRecordModel;
import com.app.model.UserModel;
import com.app.model.VoucherRecordModel;
import com.app.service.IDividedIntoRecordService;
import com.app.service.VoucherRecordService;
import com.app.vo.IntegralVoucherPageVo;
import com.app.vo.RankingVo;
import com.app.vo.VoucherIntegralRecordVo;
import com.app.vo.VoucherRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 益联券记录表
 *
 * @author 16693103420
 * @since 2024-01-26
 */
@Service
public class VoucherRecordServiceImpl extends ServiceImpl<VoucherRecordMapper, VoucherRecordModel> implements VoucherRecordService {
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VoucherRecordService voucherRecordService;
    @Autowired
    private IntegralRecordMapper integralRecordMapper;

    @Autowired
    private IDividedIntoRecordService dividedIntoRecordService;

    @Override
    public VoucherRecordVo getUserVoucherRecordList(Integer page, Integer limit, Integer userId) {
        Page<VoucherRecordModel> page1 = new Page<>(page, limit);
        QueryWrapper<VoucherRecordModel> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.orderByDesc("create_time");
        Page<VoucherRecordModel> voucherRecordPage = voucherRecordMapper.selectPage(page1, qw);
        List<VoucherRecordModel> voucherRecordList = voucherRecordPage.getRecords();

        long count = voucherRecordPage.getTotal();
        VoucherRecordVo voucherRecordVo = new VoucherRecordVo();
        voucherRecordVo.setList(voucherRecordList);
        voucherRecordVo.setCount((int) count);

        UserModel userModel = userMapper.selectById(userId);
        voucherRecordVo.setVoucher(userModel.getVoucher());
        return voucherRecordVo;
    }

    /**
     * 查询券、积分的记录（根据订单号、名称、手机号、时间范围
     *
     * @param pageSize
     * @param limit
     * @param areaId
     * @param userModel
     * @return
     */
    @Override
    public Result getVoucherIntegralRecord(String keyword, Integer ifVI, String beginTime, String endTime,
                                           Integer pageSize, Integer limit,
                                           Integer areaId, AdminUserModel userModel,String typeName) {
        List<VoucherIntegralRecordVo> vo = new ArrayList<>();
        Integer count = 0;
        Integer offset = (pageSize - 1) * limit;
        if (ifVI == null) {
            ifVI = 3;
        }
        if (userModel.getRoleId() == 3 || userModel.getRoleId() == 4) {
            areaId = userModel.getAreaId();
        }
        if (ifVI == 1) {//券
            vo = voucherRecordMapper.getVoucherIRecord(keyword, beginTime, endTime, pageSize, limit, areaId, userModel.getBusinessId(),typeName);
            for (VoucherIntegralRecordVo recordVo : vo) {
                recordVo.setIfVI(1);
            }
            if (CollectionUtil.isNotEmpty(vo)) {
                count = vo.get(0).getCount();
            }
        }
        if (ifVI == 2) {//积分
            if (userModel.getBusinessId() == null) {
                vo = voucherRecordMapper.getVIntegralRecord(keyword, beginTime, endTime, pageSize, limit, areaId, userModel.getBusinessId(),typeName);
                for (VoucherIntegralRecordVo recordVo : vo) {
                    recordVo.setIfVI(2);
                }
                if (CollectionUtil.isNotEmpty(vo)) {
                    count = vo.get(0).getCount();
                }
            }

        } else if (ifVI == 3) {
            List<VoucherIntegralRecordVo> recordVos = new ArrayList<>();
            recordVos = voucherRecordMapper.getVoucherIRecord(keyword, beginTime, endTime, pageSize, limit, areaId, userModel.getBusinessId(),typeName);
            if (recordVos.size() != 0) {
                for (VoucherIntegralRecordVo recordVo : recordVos) {
                    recordVo.setIfVI(1);
                }

                if (CollectionUtil.isNotEmpty(recordVos)) {
                    count = recordVos.get(0).getCount();
                }
            }
            if (userModel.getBusinessId() == null) {
                List<VoucherIntegralRecordVo> vo2 = voucherRecordMapper.getVIntegralRecord(keyword, beginTime, endTime, pageSize, limit, areaId, userModel.getBusinessId(),typeName);
                if (vo2.size() != 0) {
                    for (VoucherIntegralRecordVo recordVo : vo2) {
                        recordVo.setIfVI(2);
                    }
                    if (CollectionUtil.isNotEmpty(vo2)) {
                        count += vo2.get(0).getCount();
                        recordVos.addAll(vo2);
                    }

                }
            }

            vo = recordVos.subList(offset, Math.min(limit + offset, recordVos.size()));
        }
        IntegralVoucherPageVo vo0 = new IntegralVoucherPageVo();
        vo0.setList(vo);
        vo0.setCount(count);
        return Result.success(vo0);
    }

    /**
     * 券和积分的详情查询
     *
     * @param ifVI
     * @param id
     * @return
     */
    @Override
    public Result getVoucherOrIntegralById(Integer ifVI, Integer id) {
        if ((ifVI != 1 && ifVI != 2) || id == null) {
            return Result.error(400, "参数错误,请重新输入");
        }
        if (ifVI == 1) {//券
            VoucherRecordModel voucherRecordModel = voucherRecordMapper.selectByIdWithPhone(id);
            return Result.success(voucherRecordModel);
        } else {//积分
            IntegralRecordModel integralRecordModel = integralRecordMapper.selectByIdWithPhone(id);
            return Result.success(integralRecordModel);
        }

    }

    /**
     * 券的排行榜
     *
     * @return
     */
    @Override
    public Result voucherRanking(Integer businessId, Integer cityId, Integer areaId) {
        if (businessId != null) {
            List<RankingVo> list = voucherRecordMapper.voucherRankingByBusiness(businessId);
            return Result.success(list);
        } else {
            List<RankingVo> list = voucherRecordMapper.voucherRanking(businessId, cityId, areaId);
            return Result.success(list);
        }


    }

    /**
     * 券记录统计
     *
     * @param keyword   关键字
     * @param ifVI      如果vi
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @param areaId    区域id
     * @param user      用户
     * @return {@link Result}
     */
    @Override
    public Result voucherRecordStatistics(String keyword, Integer ifVI, String beginTime, String endTime, Integer areaId, AdminUserModel user,String typeName) {
        BigDecimal totalCirculationValue = BigDecimal.ZERO;
        BigDecimal totalPointsAndRecords = BigDecimal.ZERO;

        if (null == ifVI){
            ifVI = 3;
        }
        switch (ifVI) {
            case 1:
                totalCirculationValue = voucherRecordMapper.voucherRecordStatistics(keyword, beginTime, endTime, areaId, user.getBusinessId(),typeName);
                break;
            case 2:
                totalPointsAndRecords = integralRecordMapper.queryPointsSummaryData(keyword, beginTime, endTime, areaId, user.getBusinessId(),typeName);

                break;
            case 3:
                totalCirculationValue = voucherRecordMapper.voucherRecordStatistics(keyword, beginTime, endTime, areaId, user.getBusinessId(),typeName);
                totalPointsAndRecords = integralRecordMapper.queryPointsSummaryData(keyword, beginTime, endTime, areaId, user.getBusinessId(),typeName);
        }
        Map<String, BigDecimal> responseMap = new HashMap<>();
        responseMap.put("totalCirculationValue", totalCirculationValue);
        responseMap.put("totalPointsAndRecords", totalPointsAndRecords);
        return Result.success(responseMap);
    }

    /**
     * 总使用优惠券
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return {@link Object}
     */
    @Override
    public Object totalUsageCoupons(String startTime, String endTime) {

        //发放券总量
        BigDecimal amountOfCouponIssued= this.voucherRecordMapper.queryAmountCouponsIssuedByType(startTime, endTime,"益联券发放");
        BigDecimal membersOpenBonusCouponAmount= this.voucherRecordMapper.queryAmountCouponsIssuedByType(startTime, endTime,"会员开通");
        BigDecimal laXinBonusCouponAmount= this.voucherRecordMapper.queryAmountCouponsIssuedByType(startTime, endTime,"邀请好友");
        BigDecimal totalNumberOfCouponIssuedByPlatform=amountOfCouponIssued.add(membersOpenBonusCouponAmount).add(laXinBonusCouponAmount);
//choucheng
        BigDecimal integralMallVoucher= this.voucherRecordMapper.queryTotalNumberIntegralMall(startTime, endTime);
        integralMallVoucher=new BigDecimal(-integralMallVoucher.doubleValue());


        BigDecimal platformDrawing= this.dividedIntoRecordService.queryPlatformDrawing(startTime, endTime);

        Map<String,Object> responseMap=new HashMap<>();
        responseMap.put("amountOfCouponIssued",amountOfCouponIssued);
        responseMap.put("membersOpenBonusCouponAmount",membersOpenBonusCouponAmount);
        responseMap.put("laXinBonusCouponAmount",laXinBonusCouponAmount);
        responseMap.put("totalNumberOfCouponIssuedByPlatform",totalNumberOfCouponIssuedByPlatform);
        responseMap.put("totalNumberOfCouponsRecoveredByPlatform",integralMallVoucher.add(platformDrawing));

        return responseMap;
    }


    public void downLoadVoucherInfoExcel(Integer roleId, HttpServletResponse response)throws Exception{

        Double vipNum = 0.00;//vip
        Double raffle = 0.00;//抽奖
        Double grant = 0.00;//发放
        List<Map<String, Object>> list = voucherRecordMapper.getVoucherInfoList(roleId);
        for (Map<String, Object> map : list){
            String type_name = map.get("type_name").toString();
            String amount = map.get("amount").toString();
            if ("邀请好友".equals(type_name)){
                vipNum = vipNum + Double.parseDouble(amount);
            }else if ("益联券发放".equals(type_name)){
                grant = grant + Double.parseDouble(amount);
            }else if ("抽奖".equals(type_name)){
                raffle = raffle + Double.parseDouble(amount);
            }
        }
        Map<String, List<Map<String, Object>>> groupedData = list.stream()
                .collect(Collectors.groupingBy(
                        map -> map.get("area_id")+"", // 使用area_id作为key进行分组
                        Collectors.collectingAndThen(
                                Collectors.toList(), // 创建一个列表
                                listToSort -> listToSort.stream() // 对列表进行排序
                                        .sorted(Comparator.comparing(map ->map.get("area_id")+"")) // 假设someKey是你要排序的键
                                        .collect(Collectors.toList()) // 收集排序后的列表
                        )
                ));

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("平台劵");

        // 创建普通样式
        CellStyle defaultStyle = workbook.createCellStyle();
        // 设置边框
        defaultStyle.setBorderBottom(BorderStyle.THIN);
        defaultStyle.setBorderTop(BorderStyle.THIN);
        defaultStyle.setBorderLeft(BorderStyle.THIN);
        defaultStyle.setBorderRight(BorderStyle.THIN);

        //表头标题样式
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);
        Font titleFont = workbook.createFont();
        titleFont.setFontHeightInPoints((short) 16); // 设置字体大小为16点
        titleFont.setBold(true); // 设置为粗体
        titleStyle.setFont(titleFont);
        titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 为了让边框可见，你需要设置边框的颜色和线条样式（如果需要）
        defaultStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        defaultStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        defaultStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        defaultStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

        // 设置文本水平居中和垂直居中
        defaultStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        defaultStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 设置列宽
        for (int i = 0; i < 5; i++) {
            sheet.setColumnWidth(i, (short) (38 * 150) ); // 列宽设置，Apache POI中的列宽单位是1/256个字符宽度
        }

        // 创建标题行
        Row titleRow = sheet.createRow(0); // 索引为0的行作为标题行
        Cell titleCell = titleRow.createCell(0); // 跨越多列合并单元格（如果需要）
        titleCell.setCellValue("平台劵的总量");
        titleCell.setCellStyle(titleStyle);

        // 合并单元格，从第一行第一列到第一行第四列（如果你的数据有四列）
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 3); // (firstRow, lastRow, firstCol, lastCol)
        sheet.addMergedRegion(region);


        // 创建表头行
        Row headerRow = sheet.createRow(1);
        Cell headerCell = headerRow.createCell(0);
        headerCell.setCellValue("平台总券数");
        headerCell.setCellStyle(defaultStyle);

        headerCell = headerRow.createCell(1);
        headerCell.setCellValue("会员拉新赠送总量");
        headerCell.setCellStyle(defaultStyle);

        headerCell = headerRow.createCell(2);
        headerCell.setCellValue("平台活动赠送总量");
        headerCell.setCellStyle(defaultStyle);

        headerCell = headerRow.createCell(3);
        headerCell.setCellValue("会员抽奖赠送总量");
        headerCell.setCellStyle(defaultStyle);

        Row row1 = sheet.createRow(2);
        Cell row1Cell_1 = row1.createCell(0);
        row1Cell_1.setCellValue(vipNum+raffle+grant);
        row1Cell_1.setCellStyle(defaultStyle);

        Cell row1Cell_2 = row1.createCell(1);
        row1Cell_2.setCellValue(vipNum);
        row1Cell_2.setCellStyle(defaultStyle);

        Cell row1Cell_3 = row1.createCell(2);
        row1Cell_3.setCellValue(grant);
        row1Cell_3.setCellStyle(defaultStyle);

        Cell row1Cell_4 = row1.createCell(3);
        row1Cell_4.setCellValue(raffle);
        row1Cell_4.setCellStyle(defaultStyle);


        //第二行表头行
        Row headerRow_1 = sheet.createRow(3);
        Cell headerCell_1 = headerRow_1.createCell(0);
        headerCell_1.setCellValue("管辖区域总券量");
        headerCell_1.setCellStyle(defaultStyle);

        headerCell_1 = headerRow_1.createCell(1);
        headerCell_1.setCellValue("会员拉新赠送总量");
        headerCell_1.setCellStyle(defaultStyle);

        headerCell_1 = headerRow_1.createCell(2);
        headerCell_1.setCellValue("平台活动赠送总量");
        headerCell_1.setCellStyle(defaultStyle);

        headerCell_1 = headerRow_1.createCell(3);
        headerCell_1.setCellValue("会员抽奖赠送总量");
        headerCell_1.setCellStyle(defaultStyle);

        int rowNum = 4;
        for (Map.Entry<String, List<Map<String, Object>>> entry : groupedData.entrySet()) {
            String 获取areacode = entry.getKey(); // 获取areacode
            List<Map<String, Object>> areaEntries = entry.getValue();

            String areaname = "";
            Double count = 0.00;
            Double vip_amount = 0.00;//邀请会员
            Double raffle_amount = 0.00;//抽奖
            Double grade_amount = 0.00;//发放
            for (Map<String, Object> map : areaEntries){
                areaname = map.get("areaname")+"";
                String type_name = map.get("type_name")+"";
                String amount = map.get("amount")+"";
                if ("邀请好友".equals(type_name)){
                    vip_amount = vip_amount + Double.parseDouble(amount);
                }else if ("益联券发放".equals(type_name)){
                    grade_amount = grade_amount + Double.parseDouble(amount);
                }else if ("抽奖".equals(type_name)){
                    raffle_amount = raffle_amount + Double.parseDouble(amount);
                }
            }

            count = vip_amount+raffle_amount+grade_amount;
            // 创建新行
            Row row = sheet.createRow(rowNum++);
            // 写入报警类别
            Cell categoryCell = row.createCell(0);
            categoryCell.setCellValue(areaname + "( "+count+" )");
            categoryCell.setCellStyle(defaultStyle);

            Cell categoryCell1 = row.createCell(1);
            categoryCell1.setCellValue(vip_amount);
            categoryCell1.setCellStyle(defaultStyle);

            Cell categoryCell2 = row.createCell(2);
            categoryCell2.setCellValue(grade_amount);
            categoryCell2.setCellStyle(defaultStyle);

            Cell categoryCell3 = row.createCell(3);
            categoryCell3.setCellValue(raffle_amount);
            categoryCell3.setCellStyle(defaultStyle);
        }

        // 设置响应内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 设置响应头，指定文件名为下载的文件名
        String fileName = "财务报表.xlsx"; // 中文文件名
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8"); // 对文件名进行URL编码
        // 设置Content-Disposition头，同时包含filename和filename*参数
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
        // 使用ServletOutputStream写入Excel数据
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            outputStream.flush();
        }
        // 关闭工作簿
        workbook.close();

    }
}
